package com.ganbo.service.impl;

import com.ganbo.service.ILockService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 使用Redisson实现的分布式锁服务
 *
 * @author jianglongtao
 * @date 2018年8月21日
 */
@Component
@Slf4j
public class RedissonLockService implements ILockService {

    @Autowired
    private RedissonClient redissonClient;

    /**
     * 默认等待时间
     */
    @Value("${redisson.default.waitTime:120}")
    private int defaultWaitTime;

    /**
     * 默认强制释放时间
     */
    @Value("${redisson.default.leaseTime:150}")
    private int defaultLeaseTime;

    @Override
    public boolean tryLock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        try {
            return lock.tryLock(defaultWaitTime, defaultLeaseTime, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            log.warn("tryLock {} InterruptedException: {}", lockKey, e);
        }
        return false;
    }

    @Override
    public boolean tryLock(String lockKey, TimeUnit unit, int waitTime, int leaseTime) {
        RLock lock = redissonClient.getLock(lockKey);
        try {
            return lock.tryLock(waitTime, leaseTime, unit);
        } catch (InterruptedException e) {
            log.warn("tryLock {} InterruptedException: {}", lockKey, e);
        }
        return false;
    }

    @Override
    public void unlock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        try {
            lock.unlock();
        } catch (IllegalMonitorStateException e) {
            log.warn("unlock {} IllegalMonitorStateException: {}", lockKey, e);
        }
    }

    @Override
    public RLock getLockObject(String lockKey) {
        return redissonClient.getLock(lockKey);
    }

    @Override
    public void unlock(RLock lock) {
        lock.unlock();
    }

}
